import 'package:demo/common/mixin/notifier/safe_value_notifier_list.dart';
import 'package:easy_refresh/easy_refresh.dart';

import '../state/state_ctrl.dart';

class PageCtrl<T> {
  static int defaultStartIndex = 1;

  late StateCtrl stateCtrl = StateCtrl(onRefresh: refresh);

  final EasyRefreshController refreshCtrl = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);

  // 数据列表
  SafeValueNotifierList<T> list = SafeValueNotifierList([]);

  // 初始页数
  final int startIndex;

  // 当前页数
  int index = 0;

  // 刷新数据回调
  final Function(PageCtrl<T> ctrl, int index) onRefresh;

  PageCtrl({int? startIndex, required this.onRefresh}) : startIndex = startIndex ?? defaultStartIndex {
    index = this.startIndex;
  }

  void showLoading({Object? obj}) {
    stateCtrl.showLoading(obj: obj);
  }

  void showEmpty({Object? obj}) {
    stateCtrl.showEmpty(obj: obj);
  }

  void showError({Object? obj}) {
    stateCtrl.showError(obj: obj);
  }

  void refresh() {
    index = startIndex;
    onRefresh.call(this, index);
  }

  void loadMore() {
    onRefresh.call(this, index);
  }

  void addData({required List<T> data, required bool hasMore}) {
    //是否是刷新
    var isRefresh = index == startIndex;

    if (isRefresh) {
      list.value = data;

      if (data.isEmpty) {
        stateCtrl.showEmpty();
      } else {
        stateCtrl.showContent();
      }
      refreshCtrl.finishRefresh();
      refreshCtrl.resetFooter();
    } else {
      list.addAll(data);

      if (hasMore) {
        refreshCtrl.finishLoad();
      } else {
        //最后一页
        refreshCtrl.finishLoad(IndicatorResult.noMore);
      }
    }

    // 数据加载完再更新页码
    index++;
  }

  void dispose() {
    stateCtrl.dispose();
    refreshCtrl.dispose();
  }
}
